<template>
  <div class="app-container">
    <!--查询条件-->
    <el-form v-show="showSearch" :inline="true" ref="form" :model="params" label-width="68px">
      <el-form-item label="工具名称">
        <el-input style="width: 150px" size="small" v-model="params.title" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="发布状态">
        <el-select style="width: 130px" size="small" v-model="params.isPublish" filterable clearable
                   reserve-keyword
                   placeholder="是否发布" @change='handleFind'>
          <el-option
              v-for="(item) in publishList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleFind">查找</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="canAdd" size="small" class="filter-item" @click="handleAdd" type="primary"
                   icon="el-icon-plus">添加
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="small" :disabled="!multipleSelection.length" v-if="canDelBatch" class="filter-item"
                   @click="handleDelete"
                   type="danger"
                   icon="el-icon-delete">批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="queryList"></right-toolbar>
    </el-row>

    <!--表格区域-->
    <div style="margin-top: 5px">
      <el-table
          border
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column width="60" align="center" type="selection"/>
        <el-table-column
            width="120"
            align="center"
            label="封面">
          <template slot-scope="scope">
            <el-image
                class="article-cover"
                :src="scope.row.avatar"
            />
            <i id="imgIcon"
               :class="scope.row.isSecret?'el-icon-lock':'el-icon-view'"
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" align="center" label="工具名称">
          <template slot-scope="scope">
            <el-link :underline="false" @click="onClick(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column
            prop="isStick"
            align="center"
            width="120"
            label="置顶">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.isStick"
                :active-value="true"
                :inactive-value="false"
                @change="handleTop(scope)"
                active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" width="120" align="center" label="浏览量"/>
        <el-table-column prop="downloadNum" width="120" align="center" label="下载量"/>
        <el-table-column width="170" align="center" prop="createTime" sortable label="添加时间"/>
        <el-table-column width="250" align="center" label="操作">
          <template slot-scope="scope">
            <el-button v-if="canUpdate&& scope.row.isPublish" type="info" size="mini"
                       @click="offShelf(scope)">
              下架
            </el-button>
            <el-button v-if="canUpdate&& !scope.row.isPublish" type="success" size="mini"
                       @click="release(scope)">
              发布
            </el-button>
            <el-button v-if="canUpdate" type="primary" size="mini" @click="handleUpdate(scope)">编辑
            </el-button>
            <el-button v-if="canDel" size="mini" type="danger" @click="remove(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <div class="pagination-container" style="float: right;margin-bottom: 1.25rem;margin-top: 1.25rem;">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="params.pageNum" :page-size="params.pageSize" :page-sizes="[10, 20, 30]"
                       layout="total, sizes,prev, pager, next,jumper" :total="total">
        </el-pagination>
      </div>

      <!--添加or修改区域-->
      <el-dialog
          :title="title"
          :visible.sync="centerDialogVisible"
          :before-close="closeModel"
          fullscreen
          center
      >
        <el-form :rules="rules" ref="dataForm" :model="article">
          <el-row>
            <el-col :span="20">
              <el-form-item label="工具包名称" :label-width="formLabelWidth" prop="title">
                <el-input v-model="article.title" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="简介" :label-width="formLabelWidth" prop="summary">
                <el-input type="textarea" :rows="2" auto-complete="off" v-model="article.summary"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <el-form-item label="标题图" :label-width="formLabelWidth" prop="avatar">
                <el-col :span="2">
                  <el-upload
                      class="avatar-uploader1"
                      action
                      ref="upload"
                      :show-file-list="false"
                      :disabled="!canUpdate"
                      action="#"
                      :before-upload="uploadBefore"
                      :http-request="uploadSectionFile">
                    <img v-if="article.avatar"
                         :src="article.avatar"
                         class="avatar1">
                    <i v-else class="el-icon-plus avatar-uploader-icon1"></i>
                  </el-upload>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label-width="formLabelWidth" label="文件包" prop="sourceFileId">
                <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="uploadBefore"
                    :http-request="handleChange"
                    :file-list="fileList">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <!--                  <div slot="tip" class="el-upload__tip">只能上传单个文件，尽量使用压缩包</div>-->
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <el-form-item :label-width="formLabelWidth" label="是否置顶" prop="isStick">
                <el-radio v-model="article.isStick" :label="true">是</el-radio>
                <el-radio v-model="article.isStick" :label="false">否</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label-width="formLabelWidth" label="是否发布" prop="isPublish">
                <el-radio v-model="article.isPublish" :label="true">是</el-radio>
                <el-radio v-model="article.isPublish" :label="false">否</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item :label-width="formLabelWidth" label="是否私密" prop="isSecret">
                <el-radio v-model="article.isSecret" :label="true">是</el-radio>
                <el-radio v-model="article.isSecret" :label="false">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :spam="24">
              <el-form-item :label-width="formLabelWidth" label="内容" prop="contentMd">
                <mavon-editor placeholder="输入文章内容..." style="height: 600px" ref=md
                              v-model="article.contentMd" @imgDel="imgDel" @change="" @imgAdd="imgAdd"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button v-if="canAdd || canUpdate" type="primary" @click="submit">确定</el-button>
        </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {
  fetchTool,
  remove,
  update,
  top,
  save,
  info,
  deleteBatch,
  pubOrShelf
} from '@/api/tool'
import {uploadFile, delBatchFile} from '@/api/file'
import {parseTime} from '@/utils'
import {mapGetters} from 'vuex'
import {getDataByDictType} from "@/api/dictData";

export default {
  data() {
    return {
      BLOG_WEB_URL: process.env.VUE_APP_BLOG_WEB_API,
      files: {},
      visible: false,
      isEditForm: 0,
      centerDialogVisible: false,
      dialogTableVisible: false,
      showSearch: true,
      formLabelWidth: "120px",
      tableData: [],
      publishList: [],
      publishDefaultValue: null,
      total: null,
      multipleSelection: [],
      // 加载层信息
      loading: [],
      changeCount: 0,
      isChange: false,
      tags: [],
      category: [],
      title: null,
      categoryName: null,
      fileList: [],
      article: {},
      tagName: null,
      rules:
          {
            'title': [{required: true, message: '必填字段', trigger: 'blur'}],
            'summary': [{required: true, message: '必填字段', trigger: 'blur'}],
            'isSecret': [{required: true, message: '必填字段', trigger: 'change'}],
            'isStick': [{required: true, message: '必填字段', trigger: 'change'}],
            'isPublish': [{required: true, message: '必填字段', trigger: 'change'}],
            'isOriginal': [{required: true, message: '必填字段', trigger: 'change'}],
            'originalUrl': [{required: true, message: '必填字段', trigger: 'blur'}],
            'contentMd': [{required: true, message: '必填字段', trigger: 'change'}],
            'avatar': [{required: true, message: '必填字段', trigger: 'change'}],
            'toolFileId': [{required: true, message: '必填字段', trigger: 'change'}]
          },
      params: {
        title: null,
        isPublish: null,
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  created() {
    this.openLoading();
    this.getDictList();
    this.queryList();
  },
  computed: {
    ...mapGetters([
      'pres'
    ]),
    canAdd: function () {
      return true
    },
    canDel: function () {
      return true
    },
    canDelBatch: function () {
      return true
    },
    canUpdate: function () {
      return true
    },
    tagClass() {
      return function (item) {
        const index = this.article.tags.indexOf(item.name);
        return article !== -1 ? "tag-item-select" : "tag-item";
      };
    }
  },
  methods: {
    getDictList: function () {
      let dictTypes = ['sys_publish_status'];
      getDataByDictType(dictTypes).then(response => {
        let dictMap = response.data;
        this.publishList = dictMap.sys_publish_status.list
        this.publishDefaultValue = dictMap.sys_publish_status.defaultValue
      }).catch(err => {
        console.error(err)
      })
    },
    queryList: function () {
      fetchTool(this.params).then(res => {
        this.tableData = res.data.results;
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
      this.loading.close();
    },
    submit: function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.article.content = this.$refs.md.d_render
          if (this.isEditForm) {
            update(this.article).then(res => {
              this.$message.success("修改文章成功")
              this.closeDialogForm()
            }).catch(err => {
              console.log(err)
            })
          } else {
            save(this.article).then(res => {
              this.$message.success("添加文章成功")
              this.closeDialogForm()
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          this.$message.error("存在必填字段未填")
        }
      })
    },
    resetQuery: function () {
      this.params.title = null
      this.params.tagId = null
      this.params.isPublish = null
      this.queryList()
    },
    handleFind: function () {
      this.params.pageNum = 1;
      this.queryList()
    },
    release: function (scope) {
      let source = {id: scope.row.id, isPublish: 1}
      pubOrShelf(source).then(res => {
        this.$message.success("发布文章成功")
        this.queryList()
      }).catch(err => {
        console.log(err)
      })
    },
    offShelf: function (scope) {
      let source = {id: scope.row.id, isPublish: 0}
      pubOrShelf(source).then(res => {
        this.$message.success("下架文章成功")
        this.queryList()
      }).catch(err => {
        console.log(err)
      })
    },
    handleTop: function (scope) {
      let source = {
        id: scope.row.id,
        isStick: scope.row.isStick
      }
      top(source).then(res => {
        this.$message.success("置顶文章成功")
        this.queryList()
      }).catch(err => {
        console.log(err)
      })
    },
    onClick: function (row) {
      if (row.isPublish === 0) {
        this.$message.error("文章暂未发布，无法进行浏览")
        return false;
      }
      window.open(this.BLOG_WEB_URL + "articles/" + row.id);
    },
    handleSelectionChange: function (val) {
      this.multipleSelection = val;
    },
    remove: function (scope) {
      let id = scope.row.id
      this.$confirm('此操作将把文章删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(id).then(res => {
          this.$message.success("删除文章成功")
          this.queryList();
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info("取消删除")
      })

    },
    handleDelete: function () {
      let ids = []
      this.multipleSelection.forEach(item => {
        ids.push(item.id)
      })
      this.$confirm('此操作将把文章删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatch(ids).then(res => {
          this.$message.success("批量删除文章成功")
          this.queryList();
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info("取消删除")
      })

    },
    handleAdd: function () {
      this.fileList = []
      this.initModel(this.getFormObject())
    },
    initModel: function (article) {
      this.article = article
      if (this.article.id != null) {
        this.beforeShow('修改文章', 1)
      } else {
        this.beforeShow('新增文章', 0)
      }
    },
    handleUpdate: function (scope) {
      this.fileList = []
      info(scope.row.id).then(res => {
        this.article = res.data
        let file = {name: res.data.toolFileInfo.originalFileName, url: res.data.toolFileInfo.storeUrl}
        this.fileList.push(file);
        this.beforeShow("修改文章", 1)
      })
    },
    getFormObject: function () {
      return {
        id: null,
        title: '',
        avatar: '',
        summary: '',
        quantity: 0,
        content: '',
        contentMd: '',
        isSecret: false,
        isStick: false,
        isOriginal: true,
        remark: '',
        isPublish: true,
        toolFileId: null
      };
    },
    beforeShow: function (title, isEditForm) {
      this.title = title
      this.isEditForm = isEditForm
      this.centerDialogVisible = true
    },
    closeDialogForm: function () {
      this.centerDialogVisible = false
      this.queryList();
    },
    handleSizeChange: function (val) {
      this.params.pageSize = val
      this.queryList()
    },
    handleCurrentChange: function (val) {
      this.params.pageNum = val
      this.queryList()
    },
    closeModel: function (done) {
      if (this.article.title != null && this.article.title !== "") {
        this.$confirm("是否关闭博客编辑窗口", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          done();
        }).catch(() => {
          this.$message.info("已取消")
        });
      } else {
        done();
      }
    },
    uploadBefore: function () {
      this.openLoading()
    },
    uploadSectionFile: function (param) {
      uploadFile(param.file).then(res => {
        this.article.avatar = res.data.storeUrl
      })
      this.loading.close()
    },
    imgAdd: function (pos, $file) {
      uploadFile($file).then(res => {
        this.$refs.md.$img2Url(pos, res.data.storeUrl);
      }).catch(err => {
        console.log(err)
      })
    },
    imgDel: function (filename) {
      delBatchFile(filename[0].split(this.img)[1])
    },
    handleChange(param) {
      uploadFile(param.file).then(res => {
        const data = res.data;
        let file = {name: data.originalFileName, url: data.storeUrl}
        this.fileList.push(file);
        this.article.toolFileId = data.fileId;
      })
      this.loading.close()
    },
    // 打开加载层
    openLoading: function () {
      this.loading = this.$loading({
        lock: true,
        text: "正在加载中~",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    }
  }
}
</script>

<style>
.avatar-uploader1 {
  border: 1px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  width: 130px;
  height: 60px;
}

.avatar-uploader1:hover {
  border-color: #409eff;
}

.avatar-uploader-icon1 {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.avatar1 {
  width: 128px;
  height: 58px;
  display: block;
  border-radius: 10px;
}

.article-cover {
  position: relative;
  width: 100%;
  height: 60px;
  border-radius: 4px;
}

.article-cover::after {
  content: "";
  background: rgba(0, 0, 0, 0.3);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

#imgIcon {
  color: #fff;
  font-size: 1.5rem;
  position: absolute;
  right: 1rem;
  bottom: 1.4rem;
}
</style>
